﻿using System;
using System.Linq;
using Enums;
using XF.ExControls;
using XF.Common;
using System.Data;
using System.Windows.Forms;
using XF.BLL;
using System.Collections.Generic;

namespace KYBM
{
    public partial class FrmSTOCopy : XFFormEx
    {
        private readonly XF.BLL.Bill_STOHead bll = new XF.BLL.Bill_STOHead();
        private readonly XF.BLL.Base_Customer bllCustomer = new XF.BLL.Base_Customer();
        private readonly XF.BLL.Base_Materiel bllMateriel = new XF.BLL.Base_Materiel();
        private readonly XF.BLL.Bill_STOItems bllSTOItems = new XF.BLL.Bill_STOItems();
        private DataTable dtCustomer;
        private DataTable dtItem;
        private int iCustomerId = -1;
        private int iId = -1;

        public FrmSTOCopy()
        {
            InitializeComponent();
        }

        public FrmSTOCopy(int id)
        {
            InitializeComponent();
            iId = id;
        }

        private void tsBtnSure_Click(object sender, EventArgs e)
        {
            if (tbName.Focused)
            {
                ChangeCustomerCode();
            }
            if (tbCode.Focused)
            {
                ChangeCustomerName();
            }
            xfDataGridView1.EndEdit();
            string msg = CheckInput();
            if (msg.Equals(string.Empty))
            {
                SaveOrder();
            }
            else
            {
                QQMessageBox.Show(
                this,
                msg,
                MessageText.MESSAGEBOX_CAPTION_TIP,
                QQMessageBoxIcon.Information,
                QQMessageBoxButtons.OK);
            }
        }

        

        /// <summary>
        /// 保存订单
        /// </summary>
        private void SaveOrder()
        {
            XF.Model.Bill_STOHead model = new XF.Model.Bill_STOHead();
            model.OrderCode = tbOrderCode.Text;
            XF.Model.Base_Customer customer = bllCustomer.GetModelByName(tbName.Text);
            if(customer == null)
            {
                //若为新客户则新增客户信息
                customer = new XF.Model.Base_Customer();
                customer.CustomerCode = tbCode.Text;
                customer.CustomerName = tbName.Text;
                customer.PayType = zDataConverter.ToInt(cmbPayType.SelectedValue);
                customer.Remark = zDataConverter.ToString(tbCustomerRemark.Text);
                customer.Contacts = tbContacts.Text;
                customer.Phone = tbPhone.Text;
                if (tbNo.Text.Equals(string.Empty))
                {
                    customer.No = null;
                }
                else
                {
                    customer.No = zDataConverter.ToInt(tbNo.Text);
                }
                customer.Account = tbAccount.Text;
                customer.Address = tbAddress.Text;
                model.CustomerId = bllCustomer.Add(customer);
            }
            else
            {
                customer.PayType = zDataConverter.ToInt(cmbPayType.SelectedValue);
                customer.Remark = tbCustomerRemark.Text;
                customer.Contacts = tbContacts.Text;
                customer.Phone = tbPhone.Text;
                if (tbNo.Text.Equals(string.Empty))
                {
                    customer.No = null;
                }
                else
                {
                    customer.No = zDataConverter.ToInt(tbNo.Text);
                }
                customer.Account = tbAccount.Text;
                customer.Address = tbAddress.Text;
                bllCustomer.Update(customer);
                model.CustomerId = customer.Id;
            }
            model.OrderDate = dtpOrderDate.Value.Date;
            model.Remark = tbOrderRemark.Text;
            foreach(DataGridViewRow dgvr in xfDataGridView1.Rows)
            {
                if (!dgvr.IsNewRow)
                {
                    XF.Model.Bill_STOItems item = new XF.Model.Bill_STOItems();
                    item.OrderCode = model.OrderCode;
                    item.Item = dgvr.Index + 1;
                    XF.Model.Base_Materiel materiel = bllMateriel.GetModel(zDataConverter.ToString(dgvr.Cells[ColMaterielName.Name].Value), zDataConverter.ToString(dgvr.Cells[ColMaterielModel.Name].Value));
                    if (materiel == null)
                    {
                        materiel = new XF.Model.Base_Materiel();
                        materiel.MaterielName = zDataConverter.ToString(dgvr.Cells[ColMaterielName.Name].Value);
                        materiel.MaterielModel = zDataConverter.ToString(dgvr.Cells[ColMaterielModel.Name].Value);
                        item.MaterielId = bllMateriel.Add(materiel);
                    }
                    else
                    {
                        item.MaterielId = materiel.Id;
                    }
                    item.Unit = zDataConverter.ToInt(dgvr.Cells[ColUnit.Name].Value);
                    item.Qty = zDataConverter.ToDecimal(dgvr.Cells[ColQty.Name].Value);
                    item.Remark = zDataConverter.ToString(dgvr.Cells[ColRemark.Name].Value);
                    item.Supplier = zDataConverter.ToString(dgvr.Cells[ColSupplier.Name].Value);
                    model.Items.Add(item);
                }
            }
            //执行保存订单SQL
            if(bll.SaveOrder(model) == (int)SqlEnum.Success)
            {
                QQMessageBox.Show(
                this,
                MessageText.TIP_SUCCESS_PLACE,
                MessageText.MESSAGEBOX_CAPTION_TIP,
                QQMessageBoxIcon.Information,
                QQMessageBoxButtons.OK);
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                QQMessageBox.Show(
                this,
                MessageText.TIP_ERROR_PLACE,
                MessageText.MESSAGEBOX_CAPTION_TIP,
                QQMessageBoxIcon.Error,
                QQMessageBoxButtons.OK);
            }
        }

        /// <summary>
        /// 数据校验
        /// </summary>
        /// <returns>校验结果信息，为空表示校验通过</returns>
        private string CheckInput()
        {
            string msg = CheckHeadInput();
            if(msg.Equals(string.Empty))
            {
                msg = CheckItemInput();
            }
            return msg;
        }

        /// <summary>
        /// 订单抬头数据校验
        /// </summary>
        /// <returns>校验结果信息，为空表示校验通过</returns>
        private string CheckHeadInput()
        {
            if (tbCode.Text.Trim().Equals(string.Empty))
            {
                return MessageText.CHECK_ERROR_STO_CUSTOMER_CODE;
            }
            if (tbName.Text.Trim().Equals(string.Empty))
            {
                return MessageText.CHECK_ERROR_STO_CUSTOMER_NAME;
            }
            if (!tbNo.Text.Equals(string.Empty))
            {
                if (zDataConverter.ToInt(tbNo.Text, -999) == -999)
                {
                    return MessageText.CHECK_ERROR_DTO_CUSTOMER_NO;
                }
                int payType = zDataConverter.ToInt(cmbPayType.SelectedValue);
                int no = zDataConverter.ToInt(tbNo.Text, -999);
                XF.Model.Base_Customer customer = bllCustomer.GetModel(payType, no);
                if (customer != null && customer.Id != iCustomerId)
                {
                    return MessageText.CHECK_REPEAT_CUSTOMER_NO;
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// 订单明细数据校验
        /// </summary>
        /// <returns>校验结果信息，为空表示校验通过</returns>
        private string CheckItemInput()
        {
            if (xfDataGridView1.RowCount == 1 && xfDataGridView1.Rows[0].IsNewRow)
            {
                return MessageText.CHECK_ERROR_STO_ITEM_EMPTY;
            }
            else
            {
                foreach (DataGridViewRow item in xfDataGridView1.Rows)
                {
                    if (!item.IsNewRow)
                    {
                        if (zDataConverter.ToString(item.Cells[ColMaterielName.Name].Value).Equals(string.Empty))
                        {
                            return MessageText.CHECK_ERROR_STO_MATERIEL_NAME;
                        }
                        if (zDataConverter.ToDecimal(item.Cells[ColQty.Name].Value, -999) == -999)
                        {
                            return MessageText.CHECK_ERROR_STO_QTY;
                        }
                    }
                }
            }
            return string.Empty;
        }

        private void FrmSTOPlace_Load(object sender, EventArgs e)
        {
            dtCustomer = bllCustomer.GetAllList().Tables[0];
            //加载客户编号
            tbCode.AutoCompleteCustomSource.AddRange(dtCustomer.AsEnumerable().Select(d => d.Field<string>("CustomerCode")).ToArray());
            //加载客户名称
            tbName.AutoCompleteCustomSource.AddRange(dtCustomer.AsEnumerable().Select(d => d.Field<string>("CustomerName")).ToArray());
            ColUnit.DisplayMember = MessageText.LISTITEM_TEXT;
            ColUnit.ValueMember = MessageText.LISTITEM_VALUE;
            ColUnit.DataSource = GenerateData.GetUnit(false);

            cmbPayType.DisplayMember = MessageText.LISTITEM_TEXT;
            cmbPayType.ValueMember = MessageText.LISTITEM_VALUE;
            cmbPayType.DataSource = GenerateData.GetPayType(false);

            InitData();
        }

        private void InitData()
        {
            tbOrderCode.Text = bll.GetNewOrderCode(LoginInfo.MRP, DateTime.Now);
            dtpOrderDate.Value = DateTime.Now.Date;
            xfDataGridView1.Rows.Clear();
            if (iId == -1)
            {
                tbCode.Text = string.Empty;
                tbName.Text = string.Empty;
                cmbPayType.SelectedValue = 3;
                tbOrderRemark.Text = string.Empty;
                tbContacts.Text = string.Empty;
                tbPhone.Text = string.Empty;
                tbNo.Text = string.Empty;
                tbAccount.Text = string.Empty;
                tbAddress.Text = string.Empty;
            }
            else
            {
                var order = bll.GetModel(iId);
                if (order.CustomerId.HasValue)
                {
                    XF.Model.Base_Customer customer = bllCustomer.GetModel(order.CustomerId.Value);
                    if (customer != null)
                    {
                        tbCode.Text = customer.CustomerCode;
                        tbName.Text = customer.CustomerName;
                        cmbPayType.SelectedValue = customer.PayType;
                        tbOrderRemark.Text = customer.Remark;
                        tbContacts.Text = customer.Contacts;
                        tbPhone.Text = customer.Phone;
                        tbNo.Text = customer.No == null ? string.Empty : zDataConverter.ToString(customer.No);
                        tbAccount.Text = customer.Account;
                        tbAddress.Text = customer.Address;
                    }
                }
                //加载明细
                List<XF.Model.Bill_STOItems> items = bllSTOItems.DataTableToList(bllSTOItems.GetDetailList("OrderId = '" + iId + "'").Tables[0]);
                int i = 0;
                foreach (XF.Model.Bill_STOItems item in items)
                {
                    xfDataGridView1.Rows.Add();
                    xfDataGridView1.Rows[i].Cells[ColId.Name].Value = item.Id;
                    xfDataGridView1.Rows[i].Cells[ColMaterielId.Name].Value = item.MaterielId;
                    xfDataGridView1.Rows[i].Cells[ColMaterielName.Name].Value = item.MaterielName;
                    xfDataGridView1.Rows[i].Cells[ColMaterielModel.Name].Value = item.MaterielModel;
                    xfDataGridView1.Rows[i].Cells[ColUnit.Name].Value = zDataConverter.ToInt(item.Unit);
                    xfDataGridView1.Rows[i].Cells[ColQty.Name].Value = item.Qty;
                    xfDataGridView1.Rows[i].Cells[ColRemark.Name].Value = item.Remark;
                    xfDataGridView1.Rows[i].Cells[ColSupplier.Name].Value = item.Supplier;
                    i++;
                }
            }
            tbCode.Focus();
        }

        private void tsBtnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void ChangeCustomerCode()
        {
            DataRow[] rows = dtCustomer.Select("CustomerName = '" + tbName.Text + "'");
            if (rows.Length > 0)
            {
                iCustomerId = zDataConverter.ToInt(rows[0]["Id"]);
                tbCode.Text = zDataConverter.ToString(rows[0]["CustomerCode"]);
                cmbPayType.SelectedValue = zDataConverter.ToInt(rows[0]["PayType"]);
                tbCustomerRemark.Text = zDataConverter.ToString(rows[0]["Remark"]);
                tbContacts.Text = zDataConverter.ToString(rows[0]["Contacts"]);
                tbPhone.Text = zDataConverter.ToString(rows[0]["Phone"]);
                tbNo.Text = zDataConverter.ToString(rows[0]["No"]);
                tbAccount.Text = zDataConverter.ToString(rows[0]["Account"]);
                tbAddress.Text = zDataConverter.ToString(rows[0]["Address"]);
            }
            else
            {
                iCustomerId = -1;
                cmbPayType.SelectedValue = 3;
                tbCustomerRemark.Text = string.Empty;
                tbContacts.Text = string.Empty;
                tbPhone.Text = string.Empty;
                tbNo.Text = string.Empty;
                tbAccount.Text = string.Empty;
                tbAddress.Text = string.Empty;
            }
        }
        private void ChangeCustomerName()
        {
            DataRow[] rows = dtCustomer.Select("CustomerCode = '" + tbCode.Text + "'");
            if (rows.Length > 0)
            {
                iCustomerId = zDataConverter.ToInt(rows[0]["Id"]);
                tbName.Text = zDataConverter.ToString(rows[0]["CustomerName"]);
                cmbPayType.SelectedValue = zDataConverter.ToInt(rows[0]["PayType"]);
                tbCustomerRemark.Text = zDataConverter.ToString(rows[0]["Remark"]);
                tbContacts.Text = zDataConverter.ToString(rows[0]["Contacts"]);
                tbPhone.Text = zDataConverter.ToString(rows[0]["Phone"]);
                tbNo.Text = zDataConverter.ToString(rows[0]["No"]);
                tbAccount.Text = zDataConverter.ToString(rows[0]["Account"]);
                tbAddress.Text = zDataConverter.ToString(rows[0]["Address"]);

                string strWhere = string.Empty.AppendSQL(" CustomerId = " + iCustomerId);
                dtItem = bllSTOItems.GetHistoryList(strWhere).Tables[0];
            }
            else
            {
                iCustomerId = -1;
                cmbPayType.SelectedValue = 3;
                tbCustomerRemark.Text = string.Empty;
                tbContacts.Text = string.Empty;
                tbPhone.Text = string.Empty;
                tbNo.Text = string.Empty;
                tbAccount.Text = string.Empty;
                tbAddress.Text = string.Empty;
            }
        }

        private void tbName_Leave(object sender, EventArgs e)
        {
            ChangeCustomerCode();
        }

        private void tbCode_Leave(object sender, EventArgs e)
        {
            ChangeCustomerName();
        }

        private void xfDataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            int index = xfDataGridView1.RowCount - 2;
            if (index >= 0)
            {
                xfDataGridView1.Rows[index].Cells[ColUnit.Name].Value = 0;
            }
        }

        private void tsBtnMaterielDelete_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow dgvr in xfDataGridView1.SelectedRows)
            {
                xfDataGridView1.Rows.Remove(dgvr);
            }
        }

        private void xfDataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                if (e.ColumnIndex == ColMaterielModel.Index)
                {
                    FrmDialogSTOList frmDialogSTOList = new FrmDialogSTOList(iCustomerId);
                    frmDialogSTOList.Item.MaterielName = zDataConverter.ToString(xfDataGridView1.Rows[e.RowIndex].Cells[ColMaterielName.Name].Value);
                    frmDialogSTOList.Item.MaterielModel = zDataConverter.ToString(xfDataGridView1.Rows[e.RowIndex].Cells[ColMaterielModel.Name].Value);
                    frmDialogSTOList.Item.Qty = zDataConverter.ToDecimal(xfDataGridView1.Rows[e.RowIndex].Cells[ColQty.Name].Value);
                    frmDialogSTOList.Item.Unit = zDataConverter.ToInt(xfDataGridView1.Rows[e.RowIndex].Cells[ColUnit.Name].Value);
                    frmDialogSTOList.Item.Supplier = zDataConverter.ToString(xfDataGridView1.Rows[e.RowIndex].Cells[ColSupplier.Name].Value);
                    frmDialogSTOList.Item.Remark = zDataConverter.ToString(xfDataGridView1.Rows[e.RowIndex].Cells[ColRemark.Name].Value);
                    if (frmDialogSTOList.ShowDialog() == DialogResult.OK)
                    {
                        xfDataGridView1.Rows.Add();
                        xfDataGridView1.Rows[e.RowIndex].Cells[ColMaterielName.Name].Value = frmDialogSTOList.Item.MaterielName;
                        xfDataGridView1.Rows[e.RowIndex].Cells[ColMaterielModel.Name].Value = frmDialogSTOList.Item.MaterielModel;
                        xfDataGridView1.Rows[e.RowIndex].Cells[ColQty.Name].Value = frmDialogSTOList.Item.Qty;
                        xfDataGridView1.Rows[e.RowIndex].Cells[ColUnit.Name].Value = frmDialogSTOList.Item.Unit;
                        xfDataGridView1.Rows[e.RowIndex].Cells[ColSupplier.Name].Value = frmDialogSTOList.Item.Supplier;
                        xfDataGridView1.Rows[e.RowIndex].Cells[ColRemark.Name].Value = frmDialogSTOList.Item.Remark;
                    }
                }
            }
        }

        private void xfDataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (xfDataGridView1.IsCurrentCellDirty)
            {
                xfDataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

        private void FrmSTOPlace_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    tsBtnSure_Click(this, EventArgs.Empty);
                    break;
                case Keys.Escape:
                    tsBtnCancel_Click(this, EventArgs.Empty);
                    break;
            }
        }

        private void xfDataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (xfDataGridView1.CurrentCell.ColumnIndex == ColMaterielName.Index)
            {
                TextBox tb = e.Control as TextBox;
                if (tb != null && dtItem != null)
                {
                    tb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                    tb.AutoCompleteSource = AutoCompleteSource.CustomSource;
                    tb.AutoCompleteCustomSource.AddRange(dtItem.AsEnumerable().Select(d => d.Field<string>("MaterielName")).ToArray());
                }
            }
            else if (xfDataGridView1.CurrentCell.ColumnIndex == ColMaterielModel.Index)
            {
                TextBox tb = e.Control as TextBox;
                if (tb != null && dtItem != null)
                {
                    tb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                    tb.AutoCompleteSource = AutoCompleteSource.CustomSource;
                    tb.AutoCompleteCustomSource.AddRange(dtItem.AsEnumerable().Select(d => d.Field<string>("MaterielModel")).ToArray());
                }
            }
            else if (xfDataGridView1.CurrentCell.ColumnIndex == ColUnit.Index)
            {

            }
            else
            {
                TextBox tb = e.Control as TextBox;
                if (tb != null && dtItem != null)
                {
                    tb.AutoCompleteMode = AutoCompleteMode.None;
                }
            }
        }

        private void xfDataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                if (xfDataGridView1.Rows[e.RowIndex].Cells[ColQty.Index].Value == null)
                {
                    xfDataGridView1.Rows[e.RowIndex].Cells[ColQty.Index].Value = 1;
                }
            }
        }
    }
}
